package org.chameleon.lang.util;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

public class MethodUtil {
    private static final Map<String, Method> cache = new ConcurrentHashMap<>();
    protected static Method findFallbackMethod(ProceedingJoinPoint joinPoint, String fallbackMethodName) throws NoSuchMethodException{
        Method method = cache.get(fallbackMethodName);
        if (Objects.isNull(method)){
            Signature signature = joinPoint.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;
            Method currentMethod = methodSignature.getMethod();
            Class<?>[] parameterTypes = currentMethod.getParameterTypes();
            //这里通过判断必须取和原方法一样参数的fallback方法
            method =  joinPoint.getTarget().getClass().getMethod(fallbackMethodName, parameterTypes);
            cache.put(fallbackMethodName,method);
        }
        return method;
    }
}
